package simplehttpserver;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.Socket;

public class Response {
	private static final int BUFFER_SIZE = 2048;
	private OutputStream output;
	private String url;
	private String filepath;
	public Response(OutputStream output) {
		this.output = output;
	}

	public void setRequest(Request request) {
		if(request.url.equals("/")) {
			url = "/index.html";
		}else {
			url = request.url;
		}
		filepath = HttpServer.WEB_ROOT + File.separator + url;
	}

	public void sendStaticResourse() {
		byte[] bytes = new byte[BUFFER_SIZE];
		File file = new File(filepath);
		if(file.exists()) {
			FileInputStream fis=null;
			try {
				fis = new FileInputStream(file);
			} catch (FileNotFoundException e) {
				e.printStackTrace();
			}
			// 设置头部
			String success =  "HTTP/1.1 200 OK \r\n\r\n";
			try {
				output.write(success.getBytes());
			
				// 循环读取文件
				int ch = fis.read(bytes);
				while(ch!=-1) {
					System.out.println(ch);
					output.write(bytes, 0, ch);
					ch = fis.read(bytes);
				}
			} catch (IOException e) {
				e.printStackTrace();
			}
		}else {
			// 文件不存在
			String err = "HTTP/1.1 404 File Not Found\r\n"
					+ "Content-Type: text/html\r\n"
					+ "Content-Length: 23\r\n"
					+ "\r\n"
					+ "<h1>File Not Found</h1>";
			try {
				output.write(err.getBytes());
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
	}
	
	
}
